package com.keku.kplay.interceptor;

import com.keku.kplay.annotation.UserToken;
import com.keku.kplay.utils.JWTUtils;
import com.keku.kplay.utils.ResultCode;
import com.keku.kplay.utils.ResultModel;
import com.keku.kplay.utils.SecurityConstants;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 小良
 * @version 1.0
 * @date 2021/4/6 11:38
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();


        // 获取 token 中的 user id
        String userId = "";
        int code = 200;
        // 执行认证
        if (StringUtils.isNotBlank(token)) {
            try {
                Claims claims = Jwts.parser()//得到DefaultJwtParser
                        .setSigningKey(JWTUtils.getKeyInstance())//设置签名的秘钥
                        .parseClaimsJws(token.replace(SecurityConstants.TOKEN_SPLIT, "")).getBody();////设置需要解析的jwt
                userId = claims.get("userId").toString();
            } catch (SignatureException | MalformedJwtException e) {
                //解析错误
                code = 401;
            } catch (ExpiredJwtException e) {
                //超时
                code = 401;
            } catch (Exception e) {
                code = 401;
            }
        } else {
            code = 401;
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserToken.class)) {
            UserToken userToken = method.getAnnotation(UserToken.class);
            if (userToken.required()) {
                if (code == 401) {
                    ResultModel.out(response, ResultModel.failResult(ResultCode.UNAUTHORIZED, "TOKEN已过期,请重新登录"));
                    return false;
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
